<!-- 角色编辑弹窗 -->
<template>
  <div>
    <el-drawer :visible="drawerEditBoolen"
               size="50%"
               :before-close="handleClose"
               ref="drawer">
      <template v-slot:title>
        <span class="hLabel">{{ isUpdate ? '套餐卡核销记录' : '套餐卡核销记录' }}</span>
      </template>
      <div class="ele-body">
        <el-card shadow="never">
          <ele-pro-table ref="table"
                         :columns="columns"
                         :datasource="datasource"
                         tool-class="ele-toolbar-form"
                         row-key="id">
            <!-- 表头工具栏 -->
            <template v-slot:toolbar>

            </template>

            <template v-slot:style="{ row }">
              <div><img class="categoryImages"
                     :src="row.style"
                     alt="" /></div>
            </template>
            <template v-slot:content="{ row }">
              <div v-html="row.content"></div>
            </template>
            <template v-slot:status="{ row }">
              <el-switch :active-value="1"
                         :inactive-value="2"
                         v-model="row.status"
                         @change="editStatus(row)" />
            </template>
            <!-- 状态列 -->

            <template v-slot:store_name="{ row }">
              <div>
                {{ row.store_name?row.store_name:'--' }}
              </div>
            </template>
            <template v-slot:discount_money="{ row }">
              <div>
                {{ row.discount_money }}
              </div>
            </template>
            <template v-slot:num="{ row }">

              <div>{{ row.total_num-row.num }}</div>
            </template>
            <template v-slot:nums="{ row }">

              <div>{{row.num }}</div>
            </template>
            <template v-slot:userInfo="{ row }">
              <div>
                <div class="realNameStyle">
                  <img class="avaterName"
                       :src="row.logo"
                       alt="" />
                  <span>{{ row.nickname }}</span>
                </div>
              </div>

            </template>
            <!-- 操作列 -->
            <!-- <template v-slot:action="{ row }">
              <el-link type="primary"
                       :underline="false"
                       icon="el-icon-edit"
                       @click="openEdit(row)">
                查看核销记录
              </el-link>

            </template> -->
          </ele-pro-table>
          <!-- <div class="flex-column-between height83">
			  <div class="verificationRecordList margin-top_30rpx">
				<div class="flex-between  font-weight_bold margin-bottom_30rpx">
				  <div class="font-size_32rpx">
					门店：{{form.store_name?form.store_name:'--'}}
				  </div>
				  <div class="font-size_32rpx">
					{{form.total_num-form.num}}
				  </div>
				</div>
				<div class="flex-between  margin-bottom_20rpx"
					 style="color: rgb(117, 117, 117);">
				  <div class="">
					工作人员：{{form.account_name}}
				  </div>
				  <div class="">
					核销次数
				  </div>
				</div>
  
				<div class="flex-between margin-bottom_20rpx"
					 style="color: rgb(117, 117, 117);">
				  <div class="">
					工作身份：{{form.role_name}}
				  </div>
  
				</div>
				<div class="flex-between margin-bottom_20rpx"
					 style="color: rgb(117, 117, 117);">
				  <div class="">
					核销套餐卡名称：{{form.name}}
				  </div>
  
				</div>
				<div class="flex-between "
					 style="color: rgb(117, 117, 117);">
				  <div class="">
					操作时间：{{form.create_time}}
				  </div>
  
				</div>
			  </div>
			  <div class="drawer__footer">
				<el-button round
						   type="plain"
						   @click="handleClose"
						   size="medium">返回</el-button>
				<el-button type="primary"
						   round
						   :loading="loading"
						   size="medium"
						   @click="save">确定</el-button>
			  </div>
			</div> -->
        </el-card>
      </div>
    </el-drawer>
    <!-- 图片预览 -->
    <el-image-diver v-if="diverVisible"
                    style="z-index: 9999"
                    :on-close="closediver"
                    :url-list="imgdivArr" />
  </div>
</template>
  
  <script>

// import { getToken } from '@/utils/token-util';
// import {
//   userOssSignature,
//   qnyOssSignature
// } from '@/api/creatCenter/material';
// import { storageConfigDetail } from '@/api/storageInfo/index';

// import axios from 'axios';
// import {
//   siteCategoriesInsert,
//   siteCategoriesList,
//   siteCategoriesModify,
//   siteCategoriesDetail
// } from '@/api/serviceManagement/categoriesList';
import { editPackage, addPackage } from '@/api/package/index'
import { upload } from '@/api/saveImg/index'
import { packageUseLog } from '@/api/package/index'
export default {
  name: 'pictureEdit',
  components: {},
  props: {
    drawerEditBoolen: {
      type: Boolean,
      default: false
    },
    // 修改回显的数据
    data: Object
  },
  data () {
    const categoryImage = (rule, value, callback) => {
      console.log(this.form.logo);
      if (!this.form.logo) {
        callback(new Error('请上传图片'));
      } else {
        callback();
      }
    };
    const categoryStyle = (rule, value, callback) => {
      console.log(this.form.style);
      if (!this.form.style) {
        callback(new Error('请上传图片'));
      } else {
        callback();
      }
    };
    const DEFAULT_FORM = {
      id: ''
      //   store_name: '',
      //   total_num: '',
      //   num: '',
      //   account_name: "",
      //   role_name: '',
      //   name: '',
      //   create_time: ''
    };
    return {

      imageUrlStyle: '',
      fileListStyle: [],
      storageMode: '',
      options: [],
      imageUrl: '',
      imgdivArr: [],
      diverVisible: false,
      // 表单数据
      form: { ...DEFAULT_FORM },
      dialogImageUrl: '',
      fileList: [],
      dialogVisible: false,
      columns: [




        {
          prop: 'userInfo',
          label: '用户信息',
          sortable: 'custom',

          align: 'center',
          showOverflowTooltip: true,
          slot: 'userInfo'
        },
        {
          prop: 'num',
          label: '已核销次数',
          sortable: 'custom',

          align: 'center',
          showOverflowTooltip: true,
          slot: 'num'
        },
        {
          prop: 'nums',
          label: '剩余次数',
          sortable: 'custom',

          align: 'center',
          showOverflowTooltip: true,
          slot: 'nums'
        },
        {
          prop: 'total_num',
          label: '总核销数量',
          sortable: 'custom',

          align: 'center',
          showOverflowTooltip: true,

        },
        {
          prop: 'package_name',
          label: '套餐卡名字',
          sortable: 'custom',
          align: 'center',
          showOverflowTooltip: true
        },



        {
          prop: 'create_time',
          label: '创建时间',
          align: 'center',
          sortable: 'custom',
          showOverflowTooltip: false,
          formatter: (_row, _column, cellValue) => {
            return this.$util.toDateString(cellValue, 'yyyy-MM-dd HH:mm');
          }
        },

      ],
      // 表单验证规则
      rules: {
        name: [
          {
            required: true,
            message: '请输入套餐标题',
            trigger: 'blur'
          }
        ],
        desc: [
          {
            required: true,
            message: '请输入套餐副标题',
            trigger: 'blur'
          }
        ],
        price: [
          {
            required: true,
            message: '请输入价格',
            trigger: 'blur'
          }
        ],
        remark: [
          {
            required: true,
            message: '请输入充值说明',
            trigger: 'blur'
          }
        ],
        number: [
          {
            required: true,
            message: '请输入次数',
            trigger: 'blur'
          }
        ],
        // 站点 图片上传
        logo: [
          { required: true, validator: categoryImage, trigger: 'change' }
        ],
        style: [
          { required: true, validator: categoryStyle, trigger: 'change' }
        ]
      },
      editorConfig: {
        height: 525,
        relative_urls: false,
        convert_urls: false,


        images_upload_handler: async (blobInfo, success,) => {



          //  ==================================

          const files = blobInfo.blob();
          // 使用 axios 上传，实际开发这段建议写在 api 中再调用 api
          const param = new FormData();

          param.append('file', files, files.name);


          const res = await upload(param);
          console.log(res.data.url);

          success(res.data.url)



          // });
        }
      },
      // 提交状态
      loading: false,
      // 是否是修改
      isUpdate: false,
      showChoose: false,
      isCustom: false,
      backgroundStyleArr: [
        // '../../static/套餐卡背景/矩形 1590.png',
        // '../../static/套餐卡背景/矩形 1591.png',
        // '../../static/套餐卡背景/组合 907.png'
        'https://ship.admin168.net/storage/uploads/20240506/e4fc89e639dd64facbc6f62a498568de.png',
        'https://ship.admin168.net/storage/uploads/20240506/7109cb9236bdeb26079affe8f30e633a.png',
        'https://ship.admin168.net/storage/uploads/20240506/5c12c635dcd5f81ed518105e36c4977b.png'
      ],
      backgroundStyle: ''
    };
  },
  activated () {

  },
  methods: {
    /* 表格数据源 */
    datasource ({ page, limit, where }) {
      return packageUseLog({
        page,
        limit,
        // id: this.form.id,
        // ...where,

      });
    },
    /* 刷新表格 */
    reload (where) {
      this.$refs.table.reload({ page: 1, where: where });
    },
    changeStyle (e) {
      console.log(e)
      //  样式类型
      this.form.style_id = e
      if (e == 4) {
        this.isCustom = true
        if (!this.isUpdate) {
          this.fileListStyle = [];
          this.imageUrlStyle = '';
        }

      } else {
        this.isCustom = false
      }
      if (!(e == 4)) {
        this.backgroundStyle = this.backgroundStyleArr[e - 1]
        this.form.style = this.backgroundStyleArr[e - 1]
        console.log(this.backgroundStyle)
      }
    },
    // 获取存储配置
    // async storageConfig () {
    //   const res = await storageConfigDetail();

    //   // console.log(res.storageMode);

    //   this.storageMode = res?.storageMode;
    // },
    // 关闭查看器
    closediver () {
      this.diverVisible = false;
    },
    // 下载图片
    handleDownload (file) {
      window.open(file.url);
    },

    handleRemove () {
      this.fileListStyle = [];
      this.imageUrlStyle = '';
    },
    // 删除图片
    handleRemove2 () {
      this.fileList = [];
      this.imageUrl = '';
    },
    //  图片上传个数超过限制
    exceedFn () {
      this.$message({
        message: '图片上传已达到上限,请删除后再上传',
        type: 'warning'
      });
    },
    // 关闭抽屉
    handleClose () {
      console.log('查看详情');
      this.$emit('update:drawerEditBoolen', false);
    },
    async handleFileChange (file, fileList, name) {
      this.loading = true;
      console.log(this.storageMode);
      let files = file.raw;

      let param = new FormData();
      param.append('file', files, files.name);
      const res = await upload(param)
      console.log(res)
      if (res.code == 0) {
        if (name == 'backgroundStyle') {
          this.form.style = res.data.url
          this.loading = false;
        } else {
          this.form.logo = res.data.url
          console.log(this.form.logo)
          this.loading = false;
          // res.data.url

        }
      }
      // if(name=='backgroundStyle'){
      //    this.form.style=
      // }

      //   if (this.storageMode == 2) {
      //     this.aliFn(file, fileList);
      //   } else if (this.storageMode == 3) {
      //     this.qnyFn(file, fileList);
      //   }
    },
    // 阿里云
    // async aliFn (file, fileList) {
    //   this.loading = true;
    //   const res = await userOssSignature();
    //   let files = file.raw;
    //   let filename = file.name;
    //   let markIndex = filename.lastIndexOf('.');
    //   let suffix = filename.substring(markIndex);
    //   let date = new Date().getTime();
    //   // 构建请求参数
    //   let param = new FormData();
    //   param.append('key', date + suffix);
    //   param.append('policy', res.policy);
    //   param.append('OSSAccessKeyId', res.accessId);
    //   param.append('success_action_status', '200');
    //   // param.append("callback",  this.data.callback)     //回调（not)
    //   param.append('signature', res.signature);
    //   param.append('file', files, files.name);
    //   param.append('success_action_status', '200');
    //   let config = {
    //     headers: {
    //       'Access-Control-Allow-Origin': '*',
    //       'x-oss-callback-Authorization': getToken()
    //     }
    //   };
    //   console.log('suffix', suffix);

    //   let result = await axios.post(res.host, param, config);
    //   let url = res.host + '/' + date + suffix;
    //   console.log(url);
    //   this.form.categoryImages = url;
    //   this.imageUrl = url;
    //   this.loading = false;
    // },
    // async qnyFn (file, fileList) {
    //   this.loading = true;
    //   console.log(file, fileList);

    //   let files = file.raw;
    //   console.log(files);
    //   //   // 构建请求参数
    //   let param = new FormData();

    //   param.append('file', files, files.name);
    //   param.append('getsize', files.size);
    //   param.append('getContentType', files.type);
    //   param.append('getoriginalfilename', files.name);
    //   param.append('getName', files.name);

    //   const res = await qnyOssSignature(param);
    //   console.log(res.url);
    //   this.form.categoryImages = res.url;
    //   this.imageUrl = res.url;
    //   console.log('上传图片成功=======', res);
    //   this.loading = false;
    // },
    // 点击按钮预览图片
    handlePictureCardPrediv () {
      const imgStr = this.imageUrl;
      console.log(imgStr);
      if (imgStr.length) {
        if (imgStr.includes(',')) {
          console.log('字符串中包含逗号');
          // 包含的进行slice(',') 分割

          this.imgdivArr = imgStr.split(',').map((item) => item.trim());
        } else {
          console.log('字符串中不包含逗号');
          this.imgdivArr = imgStr.split();
        }

        this.diverVisible = true;
      } else {
        this.$message({
          message: '没有上传图片无法进行预览',
          type: 'warning'
        });
      }
    },
    /* 保存编辑 */
    save () {
      this.$refs['form'].validate((valid) => {
        if (!valid) {
          return false;
        }
        // if (this.isUpdate) {
        //   this.form.logo = this.imageUrl;
        //   this.form.style = this.imageUrlStyle
        // }
        const data = {
          ...this.form
        };
        console.log(data);
        this.loading = true;

        const saveOrUpdate = this.isUpdate
          ? editPackage
          : addPackage;
        saveOrUpdate(data)
          .then((msg) => {
            console.log(msg);
            this.loading = false;
            this.$message.success(msg.message);

            this.handleClose();
            this.$emit('done');
          })
          .catch((e) => {
            this.loading = false;
            this.$message.error(e.message);
          });
      });
    }
    /* 更新visible */
  },
  watch: {
    drawerEditBoolen (visible) {
      this.$nextTick(() => {
        if (visible) {
          this.isCustom = false
          console.log(this.data);
          if (this.data) {

            this.$util.assignObject(this.form, {
              ...this.data
            });

            this.reload()
            this.isUpdate = true;
          } else {
            this.isUpdate = false;

          }
        } else {
          this.$nextTick(() => {
            this.$refs['form'].resetFields();
            console.log(this.form);
          });


        }
      });
    }
  }
};
  </script>
  
  <style lang="less" scoped>
.realNameStyle {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  .avaterName {
    width: 32px;
    height: 32px;
    border-radius: 32px;
    vertical-align: middle;
    margin-right: 5px;
  }
}
/deep/.el-upload-list__item {
  transition: none !important;
  -webkit-transition: nonne !important;
}
/deep/.el-upload-list__item-name {
  transition: none !important;
  -webkit-transition: nonne !important;
}
/*隐藏input（type=number)右边的小箭头*/
/deep/.delInput input::-webkit-outer-spin-button,
/deep/.delInput input::-webkit-inner-spin-button {
  -webkit-appearance: none !important;
}
/deep/.delInput input[type='number'] {
  -moz-appearance: textfield;
}
.backgroundImg {
  height: 75px;
}
.foodsDiv div {
  margin-left: 20px;
  margin-top: 10px;
}
.height83 {
  min-height: 83vh;
}
.hLabel {
  margin: 10px 0 20px;
  font-weight: 700;
  &::before {
    content: '';
    display: inline-block;
    vertical-align: top;

    margin-right: 5px;
    height: 23px;
    width: 6px;
    background-color: #1e6ceb;
  }
}
.drawer__footer {
  display: flex;
  justify-content: flex-start;
  margin-left: 15px;
}
</style>
  